﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;

namespace Think9.Controllers.Basic
{
    [Area("SysTable")]
    public class ItemsController : BaseController
    {
        private ItemsService ItemsService = new ItemsService();
        private ItemsDetailService ItemsDetailService = new ItemsDetailService();
        private SortService SortService = new SortService();
        private ComService ComService = new ComService();

        //分类
        private SelectList SortList
        { get { return new SelectList(SortService.GetAll("ClassID,SortID,SortName", "ORDER BY SortOrder").Where(x => x.ClassID == "CAT_dict"), "SortID", "SortName"); } }

        [HttpGet]
        public override ActionResult Index(int? id)
        {
            ViewBag.SortList = SortService.GetAll("ClassID,SortID,SortName", "ORDER BY SortOrder").Where(x => x.ClassID == "CAT_dict");

            base.Index(id);
            return View();
        }

        [HttpPost]
        public JsonResult GetPageListBySearch(ItemsEntity model, PageInfoEntity pageInfo, string key, string sort)
        {
            pageInfo.field = "UpdateTime";
            pageInfo.order = "desc";

            string _sort = string.IsNullOrEmpty(sort) ? "" : sort;
            string _keywords = string.IsNullOrEmpty(key) ? "" : key;

            string str = "";
            long count;

            string where = "where 1=1 ";
            if (_sort != "")
            {
                where += " and ItemSort=@ItemSort ";
                model.ItemSort = _sort;
            }

            if (_keywords != "")
            {
                where += " and (EnCode like @EnCode OR FullName like @EnCode OR Remarks like @EnCode) ";
                model.EnCode = string.Format("%{0}%", _keywords);
            }

            long total = 0;
            IEnumerable<dynamic> list = ItemsService.GetPageByFilter(ref total, model, pageInfo, where);

            string sql = "select * from sys_sort where ClassID='CAT_dict' ORDER BY SortOrder";
            DataTable dt = ComService.GetDataTable(sql);

            foreach (Object obj in list)
            {
                if (obj is ItemsEntity)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["SortID"].ToString() == ((ItemsEntity)obj).ItemSort)
                        {
                            ((ItemsEntity)obj).ItemSort = dr["SortName"].ToString();
                        }
                    }

                    where = " where ItemCode=@ItemCode";
                    count = ComService.GetTotal("sys_itemsdetail", where, new { ItemCode = ((ItemsEntity)obj).EnCode });
                    str = count > 99 ? "{99+}" : "{" + count.ToString() + "}";

                    ((ItemsEntity)obj).Amount = str;
                }
            }

            var result = new { code = 0, msg = "", count = total, data = list };

            return Json(result);
        }

        public ActionResult Add()
        {
            ViewBag.SortList = SortList;
            return View();
        }

        [HttpPost]
        public ActionResult Add(ItemsEntity model)
        {
            model.UpdateTime = DateTime.Now;
            string err = "";

            if (ComService.GetTotal("sys_items", " where EnCode=@EnCode", new { EnCode = model.EnCode }) > 0)
            {
                err = "已存在相同字典编码";
            }

            if (err == "")
            {
                if (!ItemsService.Insert(model))
                {
                    err = "添加失败";
                }
            }

            if (err == "")
            {
                return Json(SuccessTip("添加成功"));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        [HttpGet]
        public ActionResult Edit(string id)
        {
            ViewBag.SortList = SortList;

            var model = ItemsService.GetByWhereFirst("where EnCode=@EnCode", new { EnCode = id });
            if (model != null)
            {
                return View(model);
            }
            else
            {
                return Json("数据不存在！");
            }
        }

        [HttpPost]
        public ActionResult Edit(ItemsEntity model)
        {
            model.UpdateTime = DateTime.Now;

            string where = "where EnCode='" + model.EnCode + "'";
            string updateFields = "ItemSort,FullName,OrderNo,UpdateTime,Remarks";

            var result = ItemsService.UpdateByWhere(where, updateFields, model) > 0 ? SuccessTip("编辑成功") : ErrorTip("编辑失败");
            return Json(result);
        }

        [HttpGet]
        public JsonResult Delete(string id)
        {
            string err = "";

            string where = "where EnCode='" + id + "'";
            if (ItemsService.DeleteByWhere(where))
            {
                where = "where ItemCode='" + id + "'";
                ItemsDetailService.DeleteByWhere(where);
            }

            if (err == "")
            {
                return Json(SuccessTip("删除成功"));
            }
            else
            {
                return Json(ErrorTip("删除失败"));
            }
        }

        public ActionResult ListDetail(string id)
        {
            ViewBag.ClassID = id;
            return View();
        }

        [HttpPost]
        public JsonResult GetDetailList(ItemsDetailEntity model, PageInfoEntity pageInfo, string classid)
        {
            pageInfo.field = "OrderNo";
            var result = ItemsDetailService.GetPageByFilter(model, pageInfo, "where ItemCode='" + classid + "'");
            return Json(result);
        }

        public ActionResult AddDetail(string classid)
        {
            ViewBag.ClassID = classid;

            return View();
        }

        [HttpPost]
        public ActionResult AddDetail(ItemsDetailEntity model)
        {
            string where = "where ItemCode=@ItemCode and DetailCode=@DetailCode";
            object param = new { ItemCode = model.ItemCode, DetailCode = model.DetailCode };
            if (ItemsDetailService.GetTotal(where, param) > 0)
            {
                var result = ErrorTip("添加失败!已存在相同编码");
                return Json(result);
            }
            else
            {
                var result = ItemsDetailService.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
                return Json(result);
            }
        }

        public ActionResult EditDetail(string id, string classid)
        {
            ViewBag.ClassID = classid;
            string where = "where ItemCode=@ClassID and DetailCode=@id";
            object param = new { ClassID = classid, id = id };

            var model = ItemsDetailService.GetByWhereFirst(where, param);

            if (model != null)
            {
                return View(model);
            }
            else
            {
                return Json("数据不存在！");
            }
        }

        [HttpPost]
        public ActionResult EditDetail(ItemsDetailEntity model)
        {
            string where = "where ItemCode='" + model.ItemCode + "' and DetailCode='" + model.DetailCode + "'";
            string updateFields = "DetailName,OrderNo";

            var result = ItemsDetailService.UpdateByWhere(where, updateFields, model) > 0 ? SuccessTip("编辑成功") : ErrorTip("编辑失败");

            return Json(result);
        }

        [HttpGet]
        public JsonResult DeleteDetail(string id, string classid)
        {
            string where = "where ItemCode='" + classid + "' and DetailCode='" + id + "'";
            var result = ItemsDetailService.DeleteByWhere(where) ? SuccessTip("删除成功") : ErrorTip("删除失败");
            return Json(result);
        }
    }
}